package com.mego.zbss.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

public class slideLayoutRelative extends RelativeLayout
{ 
	private GestureDetector mGestureDetector;
	private boolean bLockScrollX = false; 
	private boolean bTouchIntercept = false; 

	private OnScrollListener mOnScrollListenerCallback = null; 

	public slideLayoutRelative(Context context) {
		this(context, null); 
	} 

	public slideLayoutRelative(Context context, AttributeSet attrs) {
		this(context, attrs, 0); 
	} 

	@SuppressWarnings("deprecation")
	public slideLayoutRelative(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle); 
		mGestureDetector = new GestureDetector(new LayoutGestureListener());
	} 

	public void setOnScrollListener(OnScrollListener l){ 
		mOnScrollListenerCallback = l; 
	} 

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		bTouchIntercept = mGestureDetector.onTouchEvent(ev); 

		if(MotionEvent.ACTION_UP == ev.getAction() && !bLockScrollX){
			if(mOnScrollListenerCallback != null){ 
				mOnScrollListenerCallback.doOnRelease(); 
			} 
		} 

		return super.dispatchTouchEvent(ev); 
	} 

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		super.onInterceptTouchEvent(ev); 
		return bTouchIntercept; 
	} 
 
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		bLockScrollX = false; 
		return super.onTouchEvent(event); 
	} 

	public class LayoutGestureListener extends SimpleOnGestureListener {
		@Override
		public boolean onDown(MotionEvent e) {
			bLockScrollX = true; 
			return super.onDown(e); 
		} 

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
			if(!bLockScrollX){ 
				if(mOnScrollListenerCallback != null){ 
					mOnScrollListenerCallback.doOnScroll(e1, e2, distanceX, distanceY); 
				} 
			} 

			if(Math.abs(e1.getY() - e2.getY()) > Math.abs(e1.getX() - e2.getX())){
				return false; 
			}else{ 
				return true; 
			} 
		} 
	} 

	public interface OnScrollListener { 
		void doOnScroll(MotionEvent e1, MotionEvent e2,
                        float distanceX, float distanceY);
		void doOnRelease(); 
	} 
}
